package com.qing.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;

public class MyRandomRule extends AbstractLoadBalancerRule {
	Random rand;

	public MyRandomRule() {
		rand = new Random();
	}


	//每个服务，访问5次，换下一个服务
//	total=0 ，默认=0，如果=5，我们指向下一个服务节点
//	index=0, 默认=0，如果 total=5,index=1
	private int total=0; //被调用的次数
	private int currentIndex=0; //当前谁在提供服务

	//自定义
	public Server choose2(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			//获取还活着的服务
			List<Server> upList = lb.getReachableServers();
			//获取所有的服务
			List<Server> allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				return null;
			}
			//=============
			 if(total<5){
			 	 server=upList.get(currentIndex);
			 	 total++;
			 }else{
			 	total=0;
			 	currentIndex++;
			 	if(currentIndex>=upList.size()){
			 		currentIndex=0;
				}
			 	server=upList.get(currentIndex);
			 }

			//=============

			if (server == null) {
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}

			server = null;
			Thread.yield();
		}

		return server;

	}



	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			//获取还活着的服务
			List<Server> upList = lb.getReachableServers();
			//获取所有的服务
			List<Server> allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				return null;
			}
			//获取随机数
			int index = rand.nextInt(serverCount);
			//重活着的服务中随机获取一个
			server = upList.get(index);

			if (server == null) {
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}

			server = null;
			Thread.yield();
		}

		return server;

	}

	@Override
	public Server choose(Object key) {
		return choose2(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub

	}
}

